from flask_restful import Resource, Api
from flask import Blueprint, request
from libs.response import generate_response
from model.models import User, db
from forms.user import RegisterForm


register_api_bp = Blueprint("registerapi", __name__)
api = Api(register_api_bp)


class RegisterApi(Resource):

    def post(self):
        user_info = request.json

        # account = user_info.get("account")  # 获取账号
        # password = user_info.get("password")  # 获取密码
        # if not all([account, password]):  # 判断参数是否完整
        #     return generate_response(message="参数不完整", status_code=4000)
        #
        # user = User.query.filter(User.account == account).first()
        #
        # # 查找数据库用户是否存在
        # if user is None:
        #     user2 = User(account=account, password=password)
        #     try:
        #         db.session.add(user2)
        #         db.session.commit()
        #         return generate_response(message="用户注册成功", status_code=2000)
        #     except Exception as e:
        #         print(e)
        #         db.session.rollback()
        #         return generate_response(message="用户注册失败", status_code=4000)
        # return generate_response(message="账号已存在，请登录", status_code=4000)

        form = RegisterForm(data=user_info)
        if form.validate():
            User.create_user(
                user_info.get("account"),
                user_info.get("password")
            )
            return generate_response(message="register success")
        else:
            return generate_response(message=form.errors, status_code=4000)


api.add_resource(RegisterApi, "/registerapi")


